package com.fs.global.init;


import com.fs.entity.Role;
import com.fs.entity.User;
import com.fs.repository.RoleRepository;
import com.fs.repository.UserRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class InitData implements CommandLineRunner {

    private final UserRepository userRepository;
    private final RoleRepository roleRepository;
    private final String[] roles = new String[]{RoleName.ADMIN, RoleName.CUSTOMER, RoleName.GUEST};
    private final List<String[]> init_users = new ArrayList<String[]>() {
        {
            add(new String[]{"admin", "web管理员用户", "123456"});
            add(new String[]{"guest", "小程序访客", "654321"});
        }

    };

    public InitData(UserRepository userRepository, RoleRepository roleRepository) {
        this.userRepository = userRepository;
        this.roleRepository = roleRepository;
    }

    @Override
    public void run(String... args) throws Exception {
        List<Role> allRole = roleRepository.findAll();
        if (allRole.size() == 0) {
            Arrays.stream(roles).forEach(roleName -> {
                Role role = new Role();
                role.setName(roleName);
                roleRepository.save(role);
            });
        }

        List<User> allUser = userRepository.findAll();
        if (allUser.size() == 0) {
            for (int i = 0; i < init_users.size(); i++) {
                String[] items = init_users.get(i);
                User user = new User();
                user.setLoginName(items[0]);
                user.setName(items[1]);
                user.setPassword(items[2]);
                if (i == 0) {
                    Role role = roleRepository.findByName(RoleName.ADMIN);
                    user.getRoles().add(role);
                } else if (i == 1) {
                    Role role = roleRepository.findByName(RoleName.GUEST);
                    user.getRoles().add(role);
                }
                userRepository.save(user);
            }
        }

    }
}
